#!/usr/bin/python3

import subprocess     
import re               
import lxml  
from lxml import html 
import urllib.request  
import urllib3                                 
                                      
headers = {}
headers['User-Agent'] = 'Mozilla/5.0'
pool = urllib3.PoolManager()       
dummy='google.com'

f1 = pool.request(method='GET', url=dummy, headers=headers)
print("%s" % f1.getheaders())
htmr = f1.data
hdoc = html.document_fromstring(htmr)

inputs = hdoc.xpath('//input') 
kvs = [(elt.attrib.get('name'), elt.attrib.get('value')) for elt in inputs if elt.attrib.get('type') == 'hidden']
chk = [(elt.attrib.get('name'), "checked") for elt in inputs if elt.attrib.get('type') == 'checkbox']

forms = hdoc.xpath('//form') 
fields = dict(kvs)

href = "https://ham-wifi.maximo-it.de/login"
fields.get('link-login')

print(fields)
print(href)

f3  = pool.request_encode_body(method='POST', url=href, headers=headers, fields=fields)
# print(f3.getheaders())

coox = {}

for cookie1 in f3.getheaders().get_all('Set-Cookie'):
    cookies1 = re.findall('([^= ]*)=([^; ]*); ', cookie1)
    for (k,v) in cookies1:
        coox[k] = v

f3doc = html.document_fromstring(f3.data)

href2 = "https://ham-wifi.maximo-it.de/login"
# print(href2)

headers['Cookie'] = "; ".join(["%s=%s" % (k,v) \
                                       for (k,v) in coox.items()])
 
fields2 = {'username':'you@example.com', 'visitreason_id':10}
f4 = pool.request_encode_body(method='POST', url=href2, headers=headers, fields=fields2, encode_multipart = False)
# print(f4.getheaders())

f4doc = html.document_fromstring(f4.data)
inputs4 = f4doc.xpath('//input') 
kvs4 = [(elt.attrib.get('name'), elt.attrib.get('value')) for elt in inputs4 if elt.attrib.get('type') == 'hidden']

fields4 = dict(kvs4)


href5 = "https://gateway.maximo-it.de/login"
# it is form action indeed, should be able to extract
f5 = pool.request_encode_body(method='POST', url=href5, headers=headers, fields=fields4, encode_multipart = False)
# print(f5.getheaders())
# print(f5.data.split(b"Privacy Policy")[0])



